package com.bds.btcdc.web.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.api.TradeService;
import com.bds.btcdc.api.model.AccountInfo;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.web.model.TUser;
import com.bds.btcdc.web.service.AssetExchangeService;
import com.bds.btcdc.web.service.UserService;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.RedisUtil;
import com.bds.btcdc.web.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * Created by DongChenchen on 2018/5/16 0016
 */
public class AccountInfoTask extends Thread{
    private Logger logger = org.apache.log4j.Logger.getLogger(getClass());
    private UserService userService = SpringContextHolder.getBean(UserService.class);
    private AssetExchangeService assetExchangeService= SpringContextHolder.getBean(AssetExchangeService.class);
    private TradeService tradeService= SpringContextHolder.getBean(TradeService.class);
    public void run() {
        List<TUser> users = userService.getAll();
        for(TUser user:users) {
            try {
                Long user_id = user.getId();
                String userSessionStr = RedisUtil.getInstance().strings().get(String.valueOf(user_id));
                if (StringUtils.isBlank(userSessionStr)) {
                    continue;//只查询活跃用户
                }
                logger.info("定时任务开始查询用户："+user.getUsername()+" 的资产情况。。。");
                Result nodeResult1 = tradeService.getAccount(user_id);
                if (nodeResult1.getCode() == Const.SUC) {
                    JSONArray arrays = JSONObject.parseArray(nodeResult1.getData().toString());
                    List<AccountInfo> infos = arrays.toJavaList(AccountInfo.class);
                    //更新数据库
                    assetExchangeService.updateAccountInfos(infos);
                    logger.info("定时任务获取成功，更新数据库。。。");
                } else {
                    logger.info("定时任务执行,未获取到用户 " + user.getUsername() + " 的资产数据:" + nodeResult1.getMsg());
                }
            }catch (Exception e){
                logger.info("定时任务执行,未获取到用户 " + user.getUsername() + " 的资产数据:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
